package com.example.myaudiorecordtest;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import pub.devrel.easypermissions.EasyPermissions;

public class MainActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks{
    private final String TAG = "MainActivity";

    private AudioRecord mAudioRecord;
    private int mAudioSize;
    private Button mBtn;
    private byte[] mByte;
    private FileOutputStream mFout;
    private enum Button_State {
        BUTTON_NORMAL,
        BUTTON_START_RECORD
    };
    private Button_State mButton_State = Button_State.BUTTON_NORMAL;
    private Handler myHandler;
    private class MyRunnable implements Runnable {
        @Override
        public void run() {
            if (mAudioRecord != null) {
                mAudioRecord.startRecording();
                try {
                    mFout = openFileOutput("1.pcm", MODE_PRIVATE);
                } catch (FileNotFoundException e) {
                    Log.e(TAG, "onCreate: FileNotFoundException");
                    e.printStackTrace();
                }
                while (mButton_State == Button_State.BUTTON_START_RECORD) {
                    int readResult = mAudioRecord.read(mByte, 0, mAudioSize);
                    Log.e(TAG, "run: readResult = "+readResult );

                    for (int i = 0; i < readResult; i++) {
                        try {
                            mFout.write(mByte[i]);
                        } catch (IOException e) {
                            Log.e(TAG, "checkPermission: write");
                            e.printStackTrace();
                        }
                    }
                }
                try {
                    mFout.close();
                } catch (IOException e) {
                    Log.e(TAG, "run: mFout.close() IOException" );
                    e.printStackTrace();
                }
                Log.e(TAG, "run: 666666666666666666666" );
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mBtn = findViewById(R.id.btn);

        mAudioSize = AudioRecord.getMinBufferSize(44100,
                AudioFormat.CHANNEL_IN_MONO,
                AudioFormat.ENCODING_PCM_16BIT);
        Log.e(TAG, "onCreate: mAudioSize = "+mAudioSize );

        // AudioRecord 的创建必须等到你有了 RECORD_AUDIO 权限的时候才能创建，否则当你创建完调用startRecording的时候会报错这是一个未初始化的 AudioRecord
//        mAudioRecord = new AudioRecord(
//                MediaRecorder.AudioSource.MIC,
//                44100,
//                AudioFormat.CHANNEL_IN_MONO,
//                AudioFormat.ENCODING_PCM_16BIT,
//                mAudioSize);
        mByte = new byte[mAudioSize];

        mBtn.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mButton_State == Button_State.BUTTON_NORMAL) {
                    boolean hasPermissions = checkPermission();
                    if (hasPermissions){
                        Log.e(TAG, "onClick: hasPermissions" );
                        mButton_State = Button_State.BUTTON_START_RECORD;

                        mAudioRecord = new AudioRecord(
                                MediaRecorder.AudioSource.MIC,
                                44100,
                                AudioFormat.CHANNEL_IN_MONO,
                                AudioFormat.ENCODING_PCM_16BIT,
                                mAudioSize);
                        mHandlerThread = new HandlerThread("recordtest222");
                        mHandlerThread.start();
                        myHandler = new Handler(mHandlerThread.getLooper());
                        myHandler.post(new MyRunnable());
                    }
                } else if (mButton_State == Button_State.BUTTON_START_RECORD) {
                    Log.e(TAG, "onClick: BUTTON_START_RECORD" );
                    mButton_State = Button_State.BUTTON_NORMAL;
                    if (mHandlerThread != null){
                        mHandlerThread.quit();
                    }
                    if (myHandler != null){
                        myHandler.removeCallbacksAndMessages(null);
                    }
                    if (mAudioRecord != null){
                        mAudioRecord.stop();
                        mAudioRecord.release();
                    }
//                    mAudioRecord.release();
                    mHandlerThread = null;
                    myHandler = null;
                    mAudioRecord = null;
                }
            }
        });

    }
    private HandlerThread mHandlerThread;

    public String[] getPermissions() {
        Log.e(TAG, "getPermissions: ");
        String[] permissions = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.RECORD_AUDIO
        };
        return permissions;
    }

    private boolean checkPermission() {
        Log.e(TAG, "checkPermission: " );
        if (!EasyPermissions.hasPermissions(this, getPermissions())) {
            Log.e(TAG, "checkPermission: 申请权限" );
            EasyPermissions.requestPermissions(this, "程序运行需要存储权限", 100, getPermissions());
        } else {
            Log.e(TAG, "checkPermission: end" );
            return true;
        }
        Log.e(TAG, "checkPermission: end" );
        return false;
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        Log.e(TAG, "onPermissionsGranted: requestCode = "+requestCode+", perms = "+perms );
//        mButton_State = Button_State.BUTTON_START_RECORD;
//        mHandlerThread = new HandlerThread("recordtest222");
//        mHandlerThread.start();
//        myHandler = new Handler(mHandlerThread.getLooper());
//        myHandler.post(new MyRunnable());
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        Log.e(TAG, "onPermissionsDenied: requestCode = "+requestCode+", perms = "+perms );
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        Log.e(TAG, "onRequestPermissionsResult: requestCode = "+requestCode+", permissions = "+permissions+", grantResults = "+grantResults );
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // 将结果转发给 EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mByte = null;
    }
}